package cn.stylefeng.guns.sys.modular.system.service.impl;

import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.sys.core.util.UUIDUtils;
import cn.stylefeng.guns.sys.modular.system.entity.BtyElm;
import cn.stylefeng.guns.sys.modular.system.entity.Yybb;
import cn.stylefeng.guns.sys.modular.system.mapper.BtyElmMapper;
import cn.stylefeng.guns.sys.modular.system.model.params.BtyElmParam;
import cn.stylefeng.guns.sys.modular.system.model.result.BtyElmResult;
import  cn.stylefeng.guns.sys.modular.system.service.BtyElmService;
import cn.stylefeng.guns.sys.modular.system.service.YybbService;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.InputStream;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author liuy
 * @since 2021-08-30
 */
@Service
public class BtyElmServiceImpl extends ServiceImpl<BtyElmMapper, BtyElm> implements BtyElmService {
    @Resource
    private YybbService yybbService;
    @Override
    public void add(BtyElmParam param){
        BtyElm entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public void delete(BtyElmParam param){
        this.removeById(getKey(param));
    }

    @Override
    public void update(BtyElmParam param){
        BtyElm oldEntity = getOldEntity(param);
        BtyElm newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public BtyElmResult findBySpec(BtyElmParam param){
        return null;
    }

    @Override
    public List<BtyElmResult> findListBySpec(BtyElmParam param){
        return null;
    }

    @Override
    public LayuiPageInfo findPageBySpec(BtyElmParam param){
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param);
        return LayuiPageFactory.createPageInfo(page);
    }


    /**
     * 导入excel
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean batchImport(String fileName, MultipartFile file){
        boolean notNull = false;
        try {
            if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
                throw new Exception("上传文件格式不正确");
            }
            boolean isExcel2003 = true;
            if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
                isExcel2003 = false;
            }
            InputStream is = file.getInputStream();
            Workbook wb = null;
            if (isExcel2003) {
                wb = new HSSFWorkbook(is);
            } else {
                wb = new XSSFWorkbook(is);
            }
            //excel中多个sheet表，获取所有sheet表的数量
            //int sheets = wb.getNumberOfSheets();
            //System.out.println("sheets:"+sheets);
            //导入之前删掉之前的数据
            baseMapper.delete(new QueryWrapper<>());
            for (int i = 0; i < 1; i++) {
                //Sheet sheet = wb.getSheetAt(i);
                Sheet sheet = wb.getSheetAt(0);
                if (sheet != null) {
                    notNull = true;
                }
    
                int lastRowNum = sheet.getLastRowNum();
                for (int r = 1; r <= lastRowNum; r++) {
                    Row row = sheet.getRow(r);
                    if (row == null) {
                        continue;
                    }
                    //获取单元格
                    Cell cell = row.getCell(4);
                    if (ToolUtil.isNotEmpty(cell)) {
                        cell.setCellType(CellType.NUMERIC);
                    }
                    //入账id
                    String rzid=row.getCell(0) == null ? "" : row.getCell(0).getStringCellValue();
                    //门店id
                    String mdid = row.getCell(1) == null ? "" : row.getCell(1).getStringCellValue();
                    //店名
                    String dm = row.getCell(2) == null ? "" : row.getCell(2).getStringCellValue();
                    //账单日期
                    String zdrq = row.getCell(3) == null ? "" : row.getCell(3).getStringCellValue();
                    //结算金额
                    Double jsje = row.getCell(4) == null ? 0 : row.getCell(4).getNumericCellValue();
                    //结算日期
                    String jsrq=row.getCell(5) == null ? "" : row.getCell(5).getStringCellValue();
                    //账单类型
                    String zdlx=row.getCell(6) == null ? "" : row.getCell(6).getStringCellValue();
                    BtyElm elm=new BtyElm();
                    elm.setId(UUIDUtils.getId());
                    elm.setRzid(rzid);
                    elm.setMdid(mdid);
                    elm.setDm(dm);
                    elm.setZdrq(zdrq);
                    if(zdrq.length()>7){
                        elm.setMonth(zdrq.substring(0,7));
                    }
                    elm.setJsje(new BigDecimal(jsje).setScale(2, BigDecimal.ROUND_HALF_UP));
                    elm.setJsrq(jsrq);
                    elm.setZdlx(zdlx);
                    baseMapper.insert(elm);
                }
            }
            //导入成功之后更新饿了么结算金额到yybb中
             //baseMapper.updateYybb();
            BtyElmParam param=new BtyElmParam();
            List<BtyElmResult>list=baseMapper.elmList(param);
            BigDecimal jsje=BigDecimal.ZERO;
            for (BtyElmResult btyElmResult : list) {
                 String dm=btyElmResult.getDm();
                 String yyr=btyElmResult.getZdrq();
                 jsje=btyElmResult.getJsje();
                 Integer yybbId=btyElmResult.getYybbId();
                 String mdid=btyElmResult.getMdid();
                 Yybb yybb=yybbService.getById(yybbId);
                if(ToolUtil.isNotEmpty(yybb)){
                    if(ToolUtil.isNotEmpty(yybb.getElmsj())&&(yybb.getElmsj().compareTo(BigDecimal.ZERO)==1|yybb.getElmsj().compareTo(BigDecimal.ZERO)==-1)){
                        yybb.setElmsj(yybb.getElmsj().add(jsje));
                    }else {
                        yybb.setElmsj(jsje);
                    }
                   Boolean flag=yybbService.updateById(yybb);
                   if(flag==true){
                       List<BtyElm>listElm=baseMapper.selectList(new QueryWrapper<BtyElm>().eq("mdid",mdid));
                       if(listElm.size()>0){
                           BtyElmParam elmParam=new BtyElmParam();
                           elmParam.setMdid(listElm.get(0).getMdid());
                           elmParam.setZdrq(yyr);
                           baseMapper.updateByMdid(elmParam);
                       }
                   }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return notNull;
    }

    @Override
    public BigDecimal zje() {
        return baseMapper.zje();
    }

    @Override
    public boolean insertElm(List<BtyElm> list) {
        return baseMapper.insertElm(list);
    }

    @Override
    public List<BtyElmResult> customList(BtyElmParam param) {
        return baseMapper.customList(param);
    }


    private Serializable getKey(BtyElmParam param){
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private BtyElm getOldEntity(BtyElmParam param) {
        return this.getById(getKey(param));
    }

    private BtyElm getEntity(BtyElmParam param) {
        BtyElm entity = new BtyElm();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

}
